package com.supermap.desktop.theme;

import java.awt.Color;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DecimalFormat;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import com.supermap.data.ColorGradientType;
import com.supermap.data.Colors;
import com.supermap.data.Dataset;
import com.supermap.data.DatasetVector;
import com.supermap.data.FieldInfo;
import com.supermap.data.FieldType;
import com.supermap.data.GeoText;
import com.supermap.data.TextStyle;
//import com.supermap.data.Workspace;
import com.supermap.desktop.mapview.MapViewProperties;
import com.supermap.desktop.properties.CommonProperties;
import com.supermap.desktop.properties.CoreProperties;
import com.supermap.desktop.ui.UICommonToolkit;
import com.supermap.desktop.ui.controls.ColorsComboBox;
import com.supermap.desktop.ui.controls.DialogResult;
import com.supermap.desktop.ui.controls.InternalImageIconFactory;
import com.supermap.desktop.ui.controls.SQLExpressionDialog;
import com.supermap.desktop.ui.controls.SymbolPreViewPanel;
import com.supermap.desktop.ui.controls.TextStyleDialog;
import com.supermap.mapping.Map;
import com.supermap.mapping.RangeMode;
import com.supermap.mapping.Theme;
import com.supermap.mapping.ThemeLabel;
import com.supermap.mapping.ThemeLabelItem;

/**
 * 标签分段专题图基本设置界面
 * 
 * @author Administrator
 *
 */
class ThemeLabelRangeBasicPanel extends ThemeChangePanel {

	private static final long serialVersionUID = 1L;
	private JPanel jPanel;
	private JLabel jLabelLength;
	private JTextField fieldLength;
	private JCheckBox jCheckBoxAllVisible;
	private JComboBox<String> jComboBoxLabel;
	private JLabel jLabel;
	private SymbolPreViewPanel jPanelPreview;
	private JComboBox<String> jComboBoxPrecision;
	private JPanel jPanelToolBar;
	private JButton jButtonTextStyle;
	private JComboBox<String> jComboBoxCaption;
	private JLabel jLabelCaption;
	private JLabel jLabelPrecision;
	private JComboBox<String> jComboBoxRange;
	private JButton jButtonMerge;
	private JButton jButtonSplit;
	private JButton jButtonReverse;
	// private JComboBox<?> m_styleModalComboBox;
	private JLabel jLabelRange;
	private JComboBox<Integer> jComboBoxCount;
	private JComboBox<Colors> jComboBoxColor;
	private JComboBox<String> jComboBoxField;
	private JLabel jLabelCount;
	private JLabel jLabelColor;
	private JLabel jLabelField;
	private JTable jTable;
	private JScrollPane tableScrollPane;

	// private Workspace m_workspace;
	private String fieldInfo = "";
	private transient RangeMode rangeMode = RangeMode.EQUALINTERVAL;
	private transient DatasetVector dataset;
	private double filedCount = 5.0;
	private transient Object[][] tableData = new Object[3][4];
	private static String[] nameStrings = { MapViewProperties.getString("String_TableTitle_Field"), MapViewProperties.getString("String_TableTitle_Min"),
			MapViewProperties.getString("String_TableTitle_Max"), CoreProperties.getString("String_Caption") };
	private transient ThemeLabel labelTheme = new ThemeLabel();
	private DefaultTableModel defaultTableModel;
	private String captiontype = "<=X<";
	private String numeric = "#";
	private String labelExpresion;
	private transient Dataset[] datasets = new Dataset[1];
	private UniqueValue uniqueValue;
	private TextStyleDialog textStyleDialog;
	private SQLExpressionDialog sqlDialog;

	private String recordFieldCount;
	private String recordFieldComboBox;

	/**
	 * Create the frame
	 */
	public ThemeLabelRangeBasicPanel(SymbolPreViewPanel previewPanel, Theme themeLabel) {
		super();
		setLayout(null);
		setBounds(0, 0, 525, 325);
		initinalize(previewPanel, themeLabel);

	}

	public static String getPanelName() {
		return MapViewProperties.getString("String_PanelTitle_BasicSet");
 }

	/**
	 * 标签分段专题图初始化
	 * 
	 * @param previewPanel
	 * @param themeLabel
	 */
	private void initinalize(SymbolPreViewPanel previewPanel, Theme themeLabel) {
		// m_themeLabel = (ThemeLabel) themeLabel;
		jPanelPreview = previewPanel;
		datasets[0] = previewPanel.getDataset();
		dataset = (DatasetVector) previewPanel.getDataset();
		add(getPreviewPanel());
		add(getTopPanel());
		add(getTableScrollPane());
		add(getToolBarPanel());
		refreshTable();
		setTheme(themeLabel);
	}

	/**
	 * 加载表格的带滚动条的面板
	 * 
	 * @return m_tableScrollPane
	 */
	private JScrollPane getTableScrollPane() {
		if (tableScrollPane == null) {
			tableScrollPane = new JScrollPane();
			tableScrollPane.setBounds(250, 159, 274, 166);
			tableScrollPane.setViewportView(getTable());
		}
		return tableScrollPane;
	}

	/**
	 * Themelabel中获取表格需要的数据
	 * 
	 * @return m_tableData
	 */
	private Object[][] getData() {
		int labelCount = labelTheme.getCount();
		if (labelCount == 0) {
			return tableData = new Object[0][4];
		}
		tableData = new Object[labelCount][4];
		for (int i = 0; i < labelCount; i++) {
			ThemeLabelItem labelItem = labelTheme.getItem(i);
			TextStyle textStyle = labelItem.getStyle();
			uniqueValue = new UniqueValue();
			uniqueValue.setColor(textStyle.getForeColor());
			uniqueValue.setFlag(labelItem.isVisible());
			tableData[i][0] = uniqueValue;
			tableData[i][1] = new DecimalFormat(numeric).format(labelItem.getStart());
			tableData[i][2] = new DecimalFormat(numeric).format(labelItem.getEnd());
			tableData[i][3] = labelItem.getCaption();
		}
		tableData[0][1] = "Min";
		tableData[0][3] = "Min" + captiontype + labelTheme.getItem(0).getEnd();
		if (captiontype.contains("<")) {
			tableData[0][3] = "Min" + "<X<" + tableData[0][2];
		}
		int lastLabelCount = labelCount - 1;
		tableData[lastLabelCount][2] = "Max";
		tableData[lastLabelCount][3] = tableData[lastLabelCount][1] + captiontype + "Max";
		return tableData;
	}

	/**
	 * 表格初始化
	 * 
	 * @return m_table
	 */
	private JTable getTable() {
		if (jTable == null) {
			defaultTableModel = new DefaultTableModel(getData(), nameStrings);
			jTable = new JTable(defaultTableModel);
			jTable.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent e) {
					if (e.getButton() == 3 && e.getClickCount() == 1) {
						JPopupMenu popupMenu = new JPopupMenu();
						JMenuItem splitItem = new JMenuItem(CommonProperties.getString("String_ToolBar_Split"));
						splitItem.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent e) {
								splitItem();
							}
						});
						JMenuItem mergeItem = new JMenuItem(CommonProperties.getString("String_ToolBar_Merge"));
						mergeItem.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent e) {
								mergeItem();
							}
						});
						JMenuItem styleItem = new JMenuItem(CoreProperties.getString("String_ModifyStyle"));
						styleItem.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent e) {
								styleEdit();
							}
						});
						int count = jTable.getSelectedRowCount();
						if (count == 0) {
							splitItem.setEnabled(false);
							mergeItem.setEnabled(false);
							styleItem.setEnabled(false);
						} else if (count == 1) {
							splitItem.setEnabled(true);
							mergeItem.setEnabled(false);
							styleItem.setEnabled(true);
						} else {
							splitItem.setEnabled(true);
							mergeItem.setEnabled(true);
							styleItem.setEnabled(true);
						}
						popupMenu.add(splitItem);
						popupMenu.add(mergeItem);
						popupMenu.add(styleItem);
						popupMenu.show(jTable, e.getX(), e.getY());
					}
				}
			});
			jTable.getTableHeader().setReorderingAllowed(false);
			jTable.setRowSelectionAllowed(true);
			// m_table.setColumnSelectionAllowed(true);
			jTable.setRowHeight(25);
			refreshTable();
		}
		return jTable;
	}

	/**
	 * 刷新表格
	 */
	private void refreshTable() {
		int count = labelTheme.getCount();
		for (int i = 0; i < count; i++) {
			ThemeLabelItem labelItem = labelTheme.getItem(i);
			String caption = new DecimalFormat(numeric).format(labelItem.getStart()) + captiontype + new DecimalFormat(numeric).format(labelItem.getEnd());
			labelItem.setCaption(caption);
		}
		labelTheme.setLabelExpression(labelExpresion);
		jPanelPreview.refreshPreViewMapControl(labelTheme);
		defaultTableModel = new DefaultTableModel(getData(), nameStrings);
		jTable.setModel(defaultTableModel);
		jTable.repaint();
		TableColumn viewColumn = jTable.getColumn(MapViewProperties.getString("String_TableTitle_Field"));
		viewColumn.setPreferredWidth(50);
		viewColumn.setMaxWidth(50);
		viewColumn.setMinWidth(50);
		JPanelRenderer colorRenderer = new JPanelRenderer();
		viewColumn.setCellRenderer(colorRenderer);
		JPanelCellEditorForLabel cellEditor = new JPanelCellEditorForLabel();
		cellEditor.addPropertyChangeListener("Color", new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent evt) {
				int index = jTable.getSelectedRow();
				TextStyle textStyle = (TextStyle) evt.getNewValue();
				labelTheme.getItem(index).setStyle(textStyle);
				((UniqueValue) jTable.getValueAt(index, 0)).setColor(textStyle.getForeColor());
				jPanelPreview.refreshPreViewMapControl(labelTheme);
				jTable.repaint();
			}
		});
		cellEditor.addPropertyChangeListener("Check", new PropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent evt) {
				int index = jTable.getSelectedRow();
				boolean isVisible = (Boolean) evt.getNewValue();
				labelTheme.getItem(index).setVisible(isVisible);
				refreshTable();
			}
		});

		viewColumn.setCellEditor(cellEditor);

		jTable.getColumn(MapViewProperties.getString("String_TableTitle_Max")).setPreferredWidth(85);
		// table.getColumn("段值上限").setMaxWidth(100);
		jTable.getColumn(MapViewProperties.getString("String_TableTitle_Min")).setPreferredWidth(85);
		// table.getColumn("段值下限").setMaxWidth(100);
		jTable.getColumn(CoreProperties.getString("String_Caption")).setPreferredWidth(150);
		jTable.getModel().addTableModelListener(new TableModelListener() {

			public void tableChanged(TableModelEvent e) {
				int column = jTable.getSelectedColumn();
				int lastColumn = jTable.getColumnCount() - 1;
				if (column == lastColumn) {
					int index = jTable.getSelectedRow();
					String caption = ((String) jTable.getValueAt(index, column)).trim();
					if (caption.equals("") || caption.equals(null)) {
						String value = labelTheme.getItem(index).getCaption();
						jTable.setValueAt(value, index, column);
					} else {
						labelTheme.getItem(index).setCaption(caption);
						jTable.repaint();
					}
				}
			}
		});
	}

	/**
	 * @return
	 */
	private JLabel getFieldLabel() {
		if (jLabelField == null) {
			jLabelField = new JLabel();
			jLabelField.setBounds(10, 45, 78, 18);
			jLabelField.setText(MapViewProperties.getString("String_Label_FieldInfo"));
		}
		return jLabelField;
	}

	private JLabel getColorLabel() {
		if (jLabelColor == null) {
			jLabelColor = new JLabel();
			jLabelColor.setBounds(250, 70, 65, 18);
			jLabelColor.setText(MapViewProperties.getString("String_Label_GradualColor"));
		}
		return jLabelColor;
	}

	/**
	 * @return
	 */
	private JLabel getCountLabel() {
		if (jLabelCount == null) {
			jLabelCount = new JLabel();
			jLabelCount.setBounds(12, 95, 46, 18);
			jLabelCount.setText(MapViewProperties.getString("String_Label_RangeCount"));
		}
		return jLabelCount;
	}

	/**
	 * 字段表达式
	 * 
	 * @return m_fieldComboBox
	 */
	private JComboBox<String> getFieldComboBox() {
		if (jComboBoxField == null) {
			jComboBoxField = new JComboBox<String>();
			jComboBoxField.setEditable(true);
			jComboBoxField.setBounds(95, 45, 150, 20);
			int length = datasets.length;
			for (int i = 0; i < length; i++) {
				DatasetVector dataset = (DatasetVector) datasets[i];
				int count = dataset.getFieldCount();
				for (int j = 0; j < count; j++) {
					FieldInfo fieldInfo = dataset.getFieldInfos().get(j);
					if (fieldInfo.getType() != FieldType.TEXT) {
						String item = dataset.getName() + "." + fieldInfo.getName();
						jComboBoxField.addItem(item);
					}
				}
			}
			jComboBoxField.addItem(MapViewProperties.getString("String_Theme_Expression"));
			final int allItems = jComboBoxField.getItemCount();
			final JTextField textField = ((JTextField) jComboBoxField.getEditor().getEditorComponent());
			jComboBoxField.addItemListener(new ItemListener() {
				// 记录上一次非空的theme值
				private ThemeLabel themeLabel;

				public void itemStateChanged(ItemEvent e) {
					if (e.getStateChange() == ItemEvent.SELECTED) {
						// 判断是否为最后一项“表达式”
						if (jComboBoxField.getSelectedIndex() == jComboBoxField.getItemCount() - 1) {
							sqlDialog = new SQLExpressionDialog();
							DialogResult dialogResult = sqlDialog.showDialog(datasets);
							if (dialogResult == DialogResult.OK) {
								String filter = sqlDialog.getQueryParameter().getAttributeFilter();
								if (filter != null && !filter.trim().equals("")) {
									jComboBoxField.insertItemAt(filter, allItems - 1);
									jComboBoxField.setSelectedIndex(allItems - 1);
								}
							}
						} else {
							fieldInfo = jComboBoxField.getSelectedItem().toString();
							StringBuilder builder = new StringBuilder(fieldInfo);
							fieldInfo = builder.substring(builder.lastIndexOf(".") + 1);
						}
						if (!fieldInfo.equals(null) && !fieldInfo.trim().equals("")) {
							ThemeLabel oldTheme = null;
							if (labelTheme != null) {
								themeLabel = labelTheme;
								oldTheme = labelTheme;
							} else {
								oldTheme = themeLabel;
							}
							labelTheme = ThemeLabel.makeDefault((DatasetVector) dataset, fieldInfo, rangeMode, filedCount, ColorGradientType.GREENRED);
							if (labelTheme != null) {
								recordFieldComboBox = textField.getText();
								fireThemeChanged(new ThemeChangedEvent(this, labelTheme, oldTheme));
							}
						}
						if (labelTheme != null) {
							labelTheme.setRangeExpression(jComboBoxField.getSelectedItem().toString());
							refreshColor();
							refreshTable();
						}
					}
				}
			});

			textField.addFocusListener(new FocusListener() {
				public void focusGained(FocusEvent e) {
				}

				public void focusLost(FocusEvent e) {
					if (labelTheme == null && jComboBoxField.getSelectedIndex() != jComboBoxField.getItemCount() - 1) {
						UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_FieldInfoWrong"));
						SwingUtilities.invokeLater(new Runnable() {
							public void run() {
								textField.setText(recordFieldComboBox);
								textField.requestFocus();
								textField.selectAll();
							}
						});
					}
				}
			});
		}
		return jComboBoxField;
	}

	/**
	 * 段数
	 * 
	 * @return m_countComboBox
	 */
	private JComboBox<Integer> getCountComboBox() {
		if (jComboBoxCount == null) {
			jComboBoxCount = new JComboBox<Integer>();
			jComboBoxCount.setEditable(true);
			final JTextField textField = (JTextField) jComboBoxCount.getEditor().getEditorComponent();

			jComboBoxCount.setBounds(95, 95, 150, 20);
			for (int i = 2; i < 32; i++) {
				jComboBoxCount.addItem(i);
			}

			jComboBoxCount.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					String value = jComboBoxCount.getSelectedItem().toString();
					if ("".equals(value.trim())) {
						SwingUtilities.invokeLater(new Runnable() {
							public void run() {
								textField.setText(recordFieldCount);
							}
						});
						return;
					}

					filedCount = Integer.valueOf(jComboBoxCount.getSelectedItem().toString());
					ThemeLabelRangeBasicPanel.this.refreshByCountComboBox();
				}
			});

			textField.getDocument().addDocumentListener(new DocumentListener() {
				// 添加该变量用于优化
				private boolean isException = false;

				public void changedUpdate(DocumentEvent e) {
				}

				public void insertUpdate(DocumentEvent e) {
					int value = 1;
					try {
						value = Integer.valueOf(textField.getText());
						isException = false;
						// 处理各种情况
						if (value <= 0 || (textField.getText().indexOf("0") == 0 && textField.getText().length() > 1 || textField.getText().indexOf("-") == 0)) {
							throw new Exception();
						}
						recordFieldCount = textField.getText();
					} catch (Exception exp) {
						isException = true;
						SwingUtilities.invokeLater(new Runnable() {
							public void run() {
								textField.setText(recordFieldCount);
							}
						});
					}
					if (isException == false) {
						filedCount = Integer.valueOf(recordFieldCount);
						ThemeLabelRangeBasicPanel.this.refreshByCountComboBox();
					}
				}

				public void removeUpdate(DocumentEvent e) {
					if (isException == false) {
						if ("".equals(textField.getText())) {
							return;
						}
						if (!textField.getText().equals(recordFieldCount)) {
							recordFieldCount = textField.getText();
						}
						filedCount = Integer.valueOf(recordFieldCount);
						ThemeLabelRangeBasicPanel.this.refreshByCountComboBox();
					}
				}
			});

			textField.addFocusListener(new FocusAdapter() {
				public void focusLost(FocusEvent e) {
					if ("".equals(textField.getText().trim()) || (textField.getText().indexOf("0") == 0 && textField.getText().length() > 1)) {
						SwingUtilities.invokeLater(new Runnable() {
							public void run() {
								textField.setText(recordFieldCount);
							}
						});
					}
				}
			});
		}
		return jComboBoxCount;
	}

	private void refreshByCountComboBox() {
		ThemeLabel oldTheme = labelTheme;
		labelTheme = ThemeLabel.makeDefault((DatasetVector) dataset, fieldInfo, rangeMode, filedCount, ColorGradientType.GREENRED);
		// 此处用多线程解决专题图实际段数和选择段数不一致问题
		final int count = labelTheme.getCount();
		if (filedCount != count) {
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					ItemListener[] itemListener = jComboBoxColor.getItemListeners();
					jComboBoxColor.removeItemListener(itemListener[0]);
					JTextField textField = (JTextField) jComboBoxCount.getEditor().getEditorComponent();
					textField.setText(String.valueOf(count));
					jComboBoxColor.addItemListener(itemListener[0]);
				}
			});
		}
		fireThemeChanged(new ThemeChangedEvent(this, labelTheme, oldTheme));
		refreshColor();
		refreshTable();
	}

	private void refreshColor() {
		if (jComboBoxColor != null) {
			int colorCount = ((Colors) jComboBoxColor.getSelectedItem()).getCount();
			Colors colors = (Colors) jComboBoxColor.getSelectedItem();
			int rangeCount = labelTheme.getCount();
			if (rangeCount > 0) {
				float ratio = (1f * colorCount) / (1f * rangeCount);
				labelTheme.getItem(0).getStyle().setForeColor(colors.get(0));
				labelTheme.getItem(rangeCount - 1).getStyle().setForeColor(colors.get(colorCount - 1));
				for (int i = 1; i < rangeCount - 1; i++) {
					int temp = Math.round(i * ratio);
					if (temp == colorCount) {
						temp--;
					}
					labelTheme.getItem(i).getStyle().setForeColor(colors.get(Math.round(i * ratio)));
				}
			}
		}
	}

	/**
	 * 渐变色下拉框
	 * 
	 * @return m_colorComboBox
	 */
	@SuppressWarnings("unchecked")
	private JComboBox<Colors> getColorComboBox() {
		if (jComboBoxColor == null) {
			jComboBoxColor = new ColorsComboBox();
			jComboBoxColor.setBounds(335, 70, 170, 20);
			jComboBoxColor.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					if (e.getStateChange() == ItemEvent.SELECTED) {
						refreshColor();
						refreshTable();
					}
				}
			});
		}
		return jComboBoxColor;
	}

	/**
	 * @return
	 */
	private JLabel getRangeLabel() {
		if (jLabelRange == null) {
			jLabelRange = new JLabel();
			jLabelRange.setBounds(10, 70, 66, 18);
			jLabelRange.setText(MapViewProperties.getString("String_Label_RangeMethed"));
		}
		return jLabelRange;
	}

	/**
	 * @return
	 */
	private JButton getReverseButton() {
		if (jButtonReverse == null) {
			jButtonReverse = new JButton();
			jButtonReverse.setBounds(108, 2, 20, 20);
			jButtonReverse.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					labelTheme.reverseStyle();
					refreshTable();

				}
			});
			jButtonReverse.setMargin(new Insets(0, 0, 0, 0));
			jButtonReverse.setIcon(InternalImageIconFactory.Rever);
		}
		return jButtonReverse;
	}

	/**
	 * 分段方法
	 */
	private void splitItem() {

		int row = jTable.getSelectedRow();
		int rowCount = jTable.getRowCount();
		if (row == 0 || row == rowCount - 1) {
			UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_CantSplit"));
		} else if (row > -1) {

			ThemeLabelItem labelItem = labelTheme.getItem(row);
			double startValue = labelItem.getStart();
			double endValue = labelItem.getEnd();

			double splitValue = startValue + (endValue - startValue) / 2;
			TextStyle style1 = labelItem.getStyle();
			String caption1 = startValue + captiontype + splitValue;
			String caption2 = splitValue + captiontype + endValue;
			labelTheme.split(row, splitValue, style1, caption1, style1, caption2);
			jComboBoxCount.setSelectedIndex(jComboBoxCount.getSelectedIndex() + 1);
			refreshTable();

		} else {
			UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_Split"));
		}

	}

	/**
	 * 工具条上的拆分段按钮
	 * 
	 * @return m_splitButton
	 */
	private JButton getSplitButton() {
		if (jButtonSplit == null) {
			jButtonSplit = new JButton();
			jButtonSplit.addMouseListener(new MouseAdapter() {
				public void mouseClicked(MouseEvent e) {
					splitItem();
				}
			});
			jButtonSplit.setBounds(56, 2, 20, 20);
			// button_3.setIcon(new ImageIcon( "/icon/fen.png"));
			jButtonSplit.setMargin(new Insets(0, 0, 0, 0));
			jButtonSplit.setIcon(InternalImageIconFactory.Split);
		}
		return jButtonSplit;
	}

	/**
	 * 合并段方法
	 */
	private void mergeItem() {

		int[] row = jTable.getSelectedRows();
		if (row.length > 1) {

			int count = row[row.length - 1] - row[0] + 1;

			if (count < labelTheme.getCount() - 1) {

				ThemeLabelItem startItem = labelTheme.getItem(row[0]);
				ThemeLabelItem endItem = labelTheme.getItem(row[row.length - 1]);
				String caption = startItem.getStart() + captiontype + endItem.getEnd();
				labelTheme.merge(row[0], count, startItem.getStyle(), caption);
				int reduceCount = count - 1;
				jComboBoxCount.setSelectedIndex(jComboBoxCount.getSelectedIndex() - reduceCount);
				refreshTable();
			} else {
				UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_RquiredTwoField"));
			}
		} else {
			UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_NeedChoseTwo"));
		}

	}

	/**
	 * 工具条上的合并段按钮
	 * 
	 * @return m_mergeButton
	 */
	private JButton getM_mergeButton() {
		if (jButtonMerge == null) {
			jButtonMerge = new JButton();
			jButtonMerge.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					mergeItem();
				}
			});
			jButtonMerge.setBounds(82, 2, 20, 20);
			jButtonMerge.setMargin(new Insets(0, 0, 0, 0));
			jButtonMerge.setIcon(InternalImageIconFactory.Merge);
		}
		return jButtonMerge;
	}

	/**
	 * 分段方法
	 * 
	 * @return m_rangeComboBox
	 */
	private JComboBox<String> getRangeComboBox() {
		if (jComboBoxRange == null) {
			jComboBoxRange = new JComboBox<String>();
			jComboBoxRange.setBounds(95, 70, 150, 20);
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_EqualInterval"));
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_SquareRoot"));
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_StdDeviation"));
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_Logarithm"));
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_Quantile"));
			jComboBoxRange.addItem(MapViewProperties.getString("String_RangeMode_CustomInterval"));

			jComboBoxRange.addItemListener(new ItemListener() {

				public void itemStateChanged(ItemEvent e) {
					Object item = jComboBoxRange.getSelectedItem();
					if (item.equals(MapViewProperties.getString("String_RangeMode_EqualInterval"))) {
						rangeMode = RangeMode.EQUALINTERVAL;
						filedCount = Integer.valueOf(jComboBoxCount.getSelectedItem().toString());
						if (fieldLength.isVisible()) {
							fieldLength.setVisible(false);
							jLabelLength.setVisible(false);
						}
						if (!jComboBoxCount.isVisible()) {
							jComboBoxCount.setVisible(true);
							jLabelCount.setVisible(true);
						}
					} else if (item.equals(MapViewProperties.getString("String_RangeMode_SquareRoot"))) {
						rangeMode = RangeMode.SQUAREROOT;
						filedCount = Integer.valueOf(jComboBoxCount.getSelectedItem().toString());
						if (fieldLength.isVisible()) {
							fieldLength.setVisible(false);
							jLabelLength.setVisible(false);
						}
						if (!jComboBoxCount.isVisible()) {
							jComboBoxCount.setVisible(true);
							jLabelCount.setVisible(true);
						}
					} else if (item.equals(MapViewProperties.getString("String_RangeMode_StdDeviation"))) {
						rangeMode = RangeMode.QUANTILE;
						filedCount = Integer.valueOf(jComboBoxCount.getSelectedItem().toString());
						if (fieldLength.isVisible()) {
							fieldLength.setVisible(false);
							jLabelLength.setVisible(false);
						}
						if (!jComboBoxCount.isVisible()) {
							jComboBoxCount.setVisible(true);
							jLabelCount.setVisible(true);
						}
					} else if (item.equals(MapViewProperties.getString("String_RangeMode_Logarithm"))) {
						rangeMode = RangeMode.LOGARITHM;
						filedCount = Integer.valueOf(jComboBoxCount.getSelectedItem().toString());
						if (fieldLength.isVisible()) {
							fieldLength.setVisible(false);
							jLabelLength.setVisible(false);
						}
						if (!jComboBoxCount.isVisible()) {
							jComboBoxCount.setVisible(true);
							jLabelCount.setVisible(true);
						}
					} else if (item.equals(MapViewProperties.getString("String_RangeMode_Quantile"))) {
						rangeMode = RangeMode.STDDEVIATION;
						jComboBoxCount.setVisible(false);
						jLabelCount.setVisible(false);
						fieldLength.setVisible(false);
						jLabelLength.setVisible(false);
					} else if (item.equals(MapViewProperties.getString("String_RangeMode_CustomInterval"))) {
						rangeMode = RangeMode.CUSTOMINTERVAL;
						filedCount = Double.valueOf(fieldLength.getText());
						jComboBoxCount.setVisible(false);
						jLabelCount.setVisible(false);
						fieldLength.setVisible(true);
						jLabelLength.setVisible(true);
					} else {
						jComboBoxCount.setVisible(true);
						jLabelCount.setVisible(true);
						fieldLength.setVisible(false);
						jLabelLength.setVisible(false);
					}
					ThemeLabel oldTheme = labelTheme;
					labelTheme = ThemeLabel.makeDefault((DatasetVector) dataset, fieldInfo, rangeMode, filedCount, ColorGradientType.GREENRED);
					fireThemeChanged(new ThemeChangedEvent(this, labelTheme, oldTheme));
					refreshColor();
					refreshTable();
					jPanelPreview.refreshPreViewMapControl(labelTheme);
				}
			});

		}
		return jComboBoxRange;
	}

	/**
	 * @return
	 */
	private JLabel getPrecisionLabel() {
		if (jLabelPrecision == null) {
			jLabelPrecision = new JLabel();
			jLabelPrecision.setBounds(250, 45, 65, 20);
			jLabelPrecision.setText(MapViewProperties.getString("String_Label_FieldPrecision"));
		}
		return jLabelPrecision;
	}

	/**
	 * @return
	 */
	private JLabel getCaptionLabel() {
		if (jLabelCaption == null) {
			jLabelCaption = new JLabel();
			jLabelCaption.setBounds(250, 20, 78, 18);
			jLabelCaption.setText(MapViewProperties.getString("String_FiledFormat"));
		}
		return jLabelCaption;
	}

	/**
	 * 段标题格式
	 * 
	 * @return m_captionComboBox
	 */
	private JComboBox<String> getCaptionComboBox() {
		if (jComboBoxCaption == null) {
			jComboBoxCaption = new JComboBox<String>();
			jComboBoxCaption.setBounds(335, 20, 170, 20);
			jComboBoxCaption.addItem("0<=x<100");
			jComboBoxCaption.addItem("0-100");
			jComboBoxCaption.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					if (jComboBoxCaption.getSelectedIndex() == 0) {
						captiontype = "<=X<";
					} else {
						captiontype = "-";
					}

					refreshTable();
				}
			});
		}
		return jComboBoxCaption;
	}

	/**
	 * Textstyle修改方法
	 */
	private void styleEdit() {

		// int selectIndex = m_table.getSelectedRow();
		int[] selectIndex = jTable.getSelectedRows();
		if (selectIndex.length > 0) {
			String name = jTable.getColumnName(0);
			int width = jTable.getColumn(name).getWidth();
			int height = jTable.getTableHeader().getHeight();
			int x = jTable.getLocationOnScreen().x + width;
			int y = jTable.getLocationOnScreen().y - height;
			int dialogX = x;
			int dialogY = y;
			textStyleDialog = new TextStyleDialog();
			textStyleDialog.setLocation(dialogX, dialogY);
			textStyleDialog.setGeoText(new GeoText());
			textStyleDialog.setMapObject(new Map());
			DialogResult dialogResult = textStyleDialog.showDialog();
			if (dialogResult.equals(DialogResult.OK)) {

				TextStyle textStyle = textStyleDialog.getTextStyle();

				for (int i = 0; i < selectIndex.length; i++) {

					labelTheme.getItem(selectIndex[i]).setStyle(textStyle);
					((UniqueValue) jTable.getValueAt(selectIndex[i], 0)).setColor(textStyle.getForeColor());
				}
				jPanelPreview.refreshPreViewMapControl(labelTheme);
				jTable.repaint();
			}

		} else {
			UICommonToolkit.showMessageDialog(MapViewProperties.getString("String_Warning_ChooseColumnToSetSymbolStyle"));
		}

	}

	/**
	 * 工具条上的Textstyle修改按钮
	 * 
	 * @return m_textStyleButton
	 */
	private JButton getTextStyleButton() {
		if (jButtonTextStyle == null) {
			jButtonTextStyle = new JButton();
			jButtonTextStyle.setIcon(InternalImageIconFactory.STYLE);
			jButtonTextStyle.setBounds(27, 2, 20, 20);
			// m_textStyleButton.setText("A");
			jButtonTextStyle.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					styleEdit();
				}
			});
			jButtonTextStyle.setMargin(new Insets(0, 0, 0, 0));
		}
		return jButtonTextStyle;
	}

	/**
	 * @return
	 */
	private JPanel getToolBarPanel() {
		if (jPanelToolBar == null) {
			jPanelToolBar = new JPanel();
			jPanelToolBar.setBorder(BorderFactory.createLineBorder(Color.blue, 1));
			jPanelToolBar.setLayout(null);
			jPanelToolBar.setBounds(250, 135, 273, 24);
			jPanelToolBar.add(getSplitButton());
			jPanelToolBar.add(getM_mergeButton());
			jPanelToolBar.add(getTextStyleButton());
			jPanelToolBar.add(getReverseButton());
			// m_toolBarPanel.add(getComboBox_3());
			jPanelToolBar.add(getAllVisibleCheckBox());
		}
		return jPanelToolBar;
	}

	/**
	 * 精度
	 * 
	 * @return m_precisionComboBox
	 */
	private JComboBox<String> getPrecisionComboBox() {
		if (jComboBoxPrecision == null) {
			jComboBoxPrecision = new JComboBox<String>();
			jComboBoxPrecision.setBounds(335, 45, 170, 20);
			jComboBoxPrecision.addItem("");
			jComboBoxPrecision.addItem("1");
			jComboBoxPrecision.addItem("0.1");
			jComboBoxPrecision.addItem("0.01");
			jComboBoxPrecision.addItem("0.001");
			jComboBoxPrecision.addItem("0.0001");
			jComboBoxPrecision.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					int index = jComboBoxPrecision.getSelectedIndex();
					if (index == 0) {
						numeric = "";
					} else if (index == 1) {
						numeric = "#";
					} else if (index == 2) {
						numeric = "#.0";
					} else if (index == 3) {
						numeric = "#.00";
					} else if (index == 4) {
						numeric = "#.000";
					} else if (index == 5) {
						numeric = "#.0000";
					}
					refreshTable();
				}
			});

		}
		return jComboBoxPrecision;
	}

	/**
	 * 预览面板
	 * 
	 * @return m_previewPanel
	 */
	private SymbolPreViewPanel getPreviewPanel() {
		jPanelPreview.setBounds(0, 130, 250, 200);

		return jPanelPreview;
	}

	/**
	 * @return
	 */
	private JLabel getLabel() {
		if (jLabel == null) {
			jLabel = new JLabel();
			jLabel.setBounds(10, 20, 78, 18);
			jLabel.setText(MapViewProperties.getString("String_LabelExpression"));
		}
		return jLabel;
	}

	/**
	 * 标签表达式
	 * 
	 * @return m_labelComboBox
	 */
	private JComboBox<String> getLabelComboBox() {
		if (jComboBoxLabel == null) {
			jComboBoxLabel = new JComboBox<String>();
			jComboBoxLabel.setBounds(95, 20, 150, 20);
			jComboBoxLabel.setEditable(true);
			int length = datasets.length;
			for (int i = 0; i < length; i++) {
				DatasetVector dataset = (DatasetVector) datasets[0];
				int count = dataset.getFieldCount();
				for (int j = 0; j < count; j++) {
					FieldInfo fieldInfo = dataset.getFieldInfos().get(j);
					String item = dataset.getName() + "." + fieldInfo.getName();
					jComboBoxLabel.addItem(item);
				}
			}
			jComboBoxLabel.addItem(MapViewProperties.getString("String_Theme_Expression"));
			// final int allItems = m_labelComboBox.getItemCount();

			jComboBoxLabel.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent e) {
					if (e.getStateChange() == ItemEvent.SELECTED) {
						// if (m_labelComboBox.getItemCount() > allItems) {
						// ItemListener[] itemListeners = m_labelComboBox
						// .getItemListeners();
						// m_labelComboBox
						// .removeItemListener(itemListeners[0]);
						// m_labelComboBox.removeItemAt(m_labelAddIndex);
						// m_labelComboBox.addItemListener(itemListeners[0]);
						// }
						// 判断是否为最后一项“表达式”
						if (jComboBoxLabel.getSelectedIndex() == jComboBoxLabel.getItemCount() - 1) {
							sqlDialog = new SQLExpressionDialog();
							DialogResult dialogResult = sqlDialog.showDialog(datasets);
							if (dialogResult == DialogResult.OK) {
								String filter = sqlDialog.getQueryParameter().getAttributeFilter();
								if (!filter.equals(null) && !filter.trim().equals("")) {
									jComboBoxLabel.insertItemAt(filter, jComboBoxLabel.getItemCount() - 1);
									jComboBoxLabel.setSelectedIndex(jComboBoxLabel.getItemCount() - 2);
								}
							}
						}
						// m_labelExpresion = m_labelComboBox.getSelectedItem()
						// .toString();
						// StringBuilder builder = new StringBuilder(
						// m_labelExpresion);
						// m_labelExpresion = builder.substring(builder
						// .lastIndexOf(".") + 1);
						labelExpresion = jComboBoxLabel.getSelectedItem().toString();
						refreshTable();
					}
				}
			});

		}
		return jComboBoxLabel;
	}

	/**
	 * 全部显示的JCheckBox
	 * 
	 * @return m_allVisibleCheckBox
	 */
	private JCheckBox getAllVisibleCheckBox() {
		if (jCheckBoxAllVisible == null) {
			jCheckBoxAllVisible = new JCheckBox();
			jCheckBoxAllVisible.setSelected(true);
			jCheckBoxAllVisible.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					int count = labelTheme.getCount();
					if (jCheckBoxAllVisible.isSelected()) {
						for (int i = 0; i < count; i++) {
							labelTheme.getItem(i).setVisible(true);
						}
					} else {
						for (int i = 0; i < count; i++) {
							labelTheme.getItem(i).setVisible(false);
						}
					}
					refreshTable();
					jPanelPreview.refreshPreViewMapControl(labelTheme);
				}
			});
			jCheckBoxAllVisible.setBounds(1, 2, 20, 20);
			jCheckBoxAllVisible.setText("");
		}
		return jCheckBoxAllVisible;
	}

	/**
	 * 单段长度
	 * 
	 * @return m_lengthField
	 */
	private JTextField getLengthTextField() {
		if (fieldLength == null) {
			fieldLength = new JTextField();
			fieldLength.setBounds(95, 95, 150, 20);
			fieldLength.setVisible(false);
			fieldLength.setText("1");
			fieldLength.addCaretListener(new CaretListener() {
				String record = "0";

				public void caretUpdate(CaretEvent e) {
					String field = fieldLength.getText();
					if (!field.trim().equals("")) {
						try {
							filedCount = Double.valueOf(field);
							record = field;
							ThemeLabel oldTheme = labelTheme;
							labelTheme = ThemeLabel.makeDefault((DatasetVector) dataset, fieldInfo, rangeMode, filedCount, ColorGradientType.GREENRED);
							fireThemeChanged(new ThemeChangedEvent(this, labelTheme, oldTheme));
							if (labelTheme != null) {
								refreshColor();
								refreshTable();
							}
						} catch (Exception ept) {
							SwingUtilities.invokeLater(new Runnable() {
								public void run() {
									fieldLength.setText(record);
								}
							});
						}
					}
				}
			});
		}
		return fieldLength;
	}

	private JLabel getLengthLabel() {
		if (jLabelLength == null) {
			jLabelLength = new JLabel();
			jLabelLength.setBounds(12, 95, 46, 18);
			jLabelLength.setVisible(false);
			jLabelLength.setText(MapViewProperties.getString("String_Label_Length"));
		}
		return jLabelLength;
	}

	/**
	 * @return
	 */
	private JPanel getTopPanel() {
		if (jPanel == null) {
			jPanel = new JPanel();
			jPanel.setBorder(BorderFactory.createTitledBorder(MapViewProperties.getString("String_PanelTitle_BasicSet")));
			jPanel.setLayout(null);
			jPanel.setBounds(0, 5, 524, 129);
			jPanel.add(getCaptionLabel());
			jPanel.add(getPrecisionLabel());
			jPanel.add(getColorLabel());
			jPanel.add(getColorComboBox());
			jPanel.add(getPrecisionComboBox());
			jPanel.add(getCaptionComboBox());
			jPanel.add(getFieldLabel());
			jPanel.add(getCountLabel());
			jPanel.add(getFieldComboBox());
			jPanel.add(getCountComboBox());
			jPanel.add(getRangeLabel());
			jPanel.add(getRangeComboBox());
			jPanel.add(getLabel());
			jPanel.add(getLabelComboBox());
			jPanel.add(getLengthTextField());
			jPanel.add(getLengthLabel());
		}
		return jPanel;
	}

	/**
	 * 重新设置专题图
	 */
	protected void setTheme(Theme theme) {
		ThemeLabel themeLabel = (ThemeLabel) theme;
		if (!labelTheme.equals(themeLabel)) {

			labelTheme = (ThemeLabel) theme;
			int count = labelTheme.getCount();
			if (count != 0) {
				// 渐变颜色框，此处暂时采取自己生成后添加上去，模拟记忆
				Color[] gradientColors = new Color[labelTheme.getCount()];
				for (int i = 0; i < count; i++) {
					gradientColors[i] = labelTheme.getItem(i).getStyle().getForeColor();
				}
				Colors colors = Colors.makeGradient(labelTheme.getCount(), gradientColors);
				// 插入到自定义前面，并使之选中
				int index = jComboBoxColor.getItemCount() - 2;
				jComboBoxColor.insertItemAt(colors, index);
				ItemListener[] itemListener = jComboBoxColor.getItemListeners();
				jComboBoxColor.removeItemListener(itemListener[0]);
				jComboBoxColor.setSelectedIndex(index);
				jComboBoxColor.addItemListener(itemListener[0]);

				// 初始化标签表达式
				String labelValue = labelTheme.getLabelExpression();
				for (int i = 0; i < jComboBoxLabel.getItemCount(); i++) {
					if (jComboBoxLabel.getItemAt(i).toString().indexOf(labelValue) != -1) {
						jComboBoxLabel.setSelectedItem(jComboBoxLabel.getItemAt(i));
						break;
					}
				}

				// 初始化分段
				fieldInfo = labelTheme.getRangeExpression();
				jComboBoxField.setSelectedItem(fieldInfo);

				rangeMode = labelTheme.getRangeMode();
				if (jComboBoxRange.getSelectedIndex() != rangeMode.value()) {
					jComboBoxRange.setSelectedIndex(rangeMode.value());
				}

				filedCount = labelTheme.getCount();
				if (!jComboBoxCount.getSelectedItem().equals(labelTheme.getCount())) {
					jComboBoxCount.setSelectedItem(labelTheme.getCount());
				}
				if (rangeMode.equals(RangeMode.CUSTOMINTERVAL)) {
					double start = labelTheme.getItem(1).getStart();
					double end = labelTheme.getItem(1).getEnd();
					double length = end - start;
					fieldLength.setText(String.valueOf(length));

				}
			}
		}
	}

	/**
	 * 返回专题图
	 */
	protected Theme gettheme() {
		return labelTheme;
	}

}
